import axios from "axios";
import { getToken } from "@/utils";
import store from "@/store";
import router from "@/router";

const service = axios.create({
  baseURL: process.env.API_ORIGIN,
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000, // request timeout
});
service.interceptors.request.use((config) => {
  console.log("interceptors.request", config);
  config.headers["Auth"] = getToken();
  config.headers["Platform"] = process.env.PLARFORM;
  return config;
});
service.interceptors.response.use(
  (response) => {
    console.log("interceptors.response", response);
    const { url } = response.config;
    // 如果传入的url本身带有hostname, 说明是外链接口
    if (/^https?/.test(url)) {
      return Promise.resolve(response.data);
    }

    const res = response.data;
    if (res.code + "" === "200") {
      return Promise.resolve(res);
    }

    if (res.code + "" === "401" || res.code + "" === "403") {
      res.msg = "登录信息失效, 请重新登录";
      store.dispatch("app/login");
      router.push({
        name: "login",
      });
      return Promise.reject(res);
    }
    // console.log("interceptors.request", res);
    return Promise.reject(res); // 返回的是业务层数据,走向实例的then部分
  },
  async (error) => {
    console.log("http error", error);
    let res = {};

    if (!error.response) {
      res = {
        code: 500,
        msg: "网络出现异常，请重试......",
        status: "error",
      };
      return Promise.reject(res);
    }

    res = {
      code: 500,
      msg: error.response.message || "系统出现异常，请稍后重试",
      status: error.response.status,
    };
    return Promise.reject(res);
  }
);

// 重新封装类的目的是输出请求和返回的数据
class Http {
  async execute(config) {
    console.log("excure config", config);
    const { desc, url } = config;
    if (!desc) {
      console.error("缺少接口描述参数");
      return Promise.reject(); // 走向业务层的catch部分
    }
    if (!url) {
      console.error("缺少接口地址");
      return Promise.reject(); // 走向业务层的catch部分
    }
    return new Promise((resolve, reject) => {
      service(config)
        .then((res) => {
          resolve(res);
        })
        .catch((err) => {
          // 走向业务层的catch部分
          reject(err);
        });
    });
  }
  async get(config) {
    const { data: params } = config;

    return await this.execute({ ...config, method: "GET", params });
  }
  async post(config = { desc: "", url: "", data: {}, headers: {} }) {
    return await this.execute({ method: "POST", ...config });
  }
  async file(config = { desc: "", url: "", data: {}, headers: {} }) {
    return await this.execute({
      method: "POST",
      ...config,
      header: { "Content-Type": "multipart/form-data;charset=UTF-8" },
    });
  }
  mock({ desc = "Mock", data = {} }) {
    console.warn("Mock: " + desc, {
      code: 200,
      data,
    });
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve({
          code: 200,
          data,
        });
      }, 1000);
    });
  }
}
export default new Http();
